package com.lagou.base;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //1.获取参数
            //获取要调用的方法名
            resp.setContentType("text/html;charset=utf-8");
            String methodName = req.getParameter("methodName");

            //2.业务处理
//            if(methodName != null){
                //通过反射优化代码,提升代码的可维护性
                //1.获取字节码对象  this = TestServlet对象
                Class c = this.getClass();
                Method method=null;
                //2.根据传入的方法名, 获取对应方法对象,执行方法即可
                method= c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);

                //3.调用Method对象的 invoke()方法,执行对应的功能
                method.invoke(this,req,resp);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
